<template>
  <div class="login-container">
    <div class="main">
      <div class="zb">
        <img src="@/assets/images/login/logo.png" /><br />
        <p>办公一体化管理平台[简称：办公管理平台]V1.0</p>
      </div>
      <div class="yb">
        <div class="zzb">
          <p>
            手机扫码登录<br />
            打开微信App在左上角打开扫一扫
          </p>
          <div class="Qrcode">
            <img src="@/assets/images/login/Qrcode-img.png" />
          </div>
        </div>
        <div class="yyb">
          <h4>密码登录</h4>
          <el-form
            v-show="active == 1"
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            autocomplete="on"
            label-position="center"
          >
            <el-form-item prop="account">
              <el-input
                ref="account"
                v-model="loginForm.account"
                :placeholder="$t('login.username')"
                name="account"
                type="text"
                tabindex="1"
                autocomplete="on"
                prefix-icon="el-icon-user"
                size="large"
                @change="getConfig"
                style="margin-left:40px;width:80%"
              ></el-input>
            </el-form-item>
            <el-form-item class="rule-tip" style="margin-left:40px;width:80%">{{
              $t("login.rule")
            }}</el-form-item>
            <el-tooltip
              v-model="capsTooltip"
              :content="$t('login.upper')"
              placement="right"
              manual
            >
              <el-form-item prop="password">
                <el-input
                  ref="password"
                  v-model="loginForm.password"
                  show-password
                  :placeholder="$t('login.password')"
                  name="password"
                  tabindex="2"
                  autocomplete="on"
                  @keyup.native="checkCapslock"
                  @blur="capsTooltip = false"
                  prefix-icon="el-icon-lock"
                  size="large"
                  style="margin-left:40px;width:80%"
                ></el-input>
                <!-- @keyup.enter.native="handleLogin" -->
              </el-form-item>
            </el-tooltip>

            <el-button
              :loading="loading"
              type="primary"
              class="login-btn"
              size="large"
              @click.native.prevent="handleLogin"
              >{{ $t("login.logIn") }}</el-button
            >
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
@import "./index.scss";
</style>

<script>
import { getConfig } from "@/api/user";
export default {
  name: "Login",
  data() {
    return {
      loginForm: {
        account: "",
        password: "",
        code: "",
        origin: "password"
      },
      loginRules: {
        account: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("login.accountTip")
          }
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("login.passwordTip")
          }
        ],
        code: [
          { required: true, trigger: "blur", message: this.$t("login.codeTip") }
        ]
      },
      imgUrl: "",
      timestamp: "",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      needCode: false,
      codeLength: 4,
      redirect: undefined,
      showTxt: false,
      otherQuery: {},
      active: 1
    };
  },
  computed: {
    sysConfig() {
      return this.$store.state.settings.sysConfig;
    },
    loginLoading() {
      return this.$store.state.user.loginLoading;
    }
  },
  watch: {
    loginLoading(val) {
      if (!val) this.loading = false;
    },
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  created() {
    const _this = this;
    document.onkeydown = function(e) {
      const { keyCode } = e;
      if (keyCode === 13) {
        _this.handleLogin();
      }
    };
    if (this.needCode) this.changeImg();
  },
  mounted() {
    this.$store.commit("user/SET_LOGIN_LOADING", false);
    this.setShowTxt();
    window.onresize = () => {
      this.setShowTxt();
    };
  },
  destroyed() {
    document.onkeydown = function(e) {
      const { keyCode } = e;
      if (keyCode === 13) {
      }
    };
  },
  methods: {
    setShowTxt() {
      if (document.documentElement.clientHeight <= 840) {
        this.showTxt = false;
      } else {
        this.showTxt = true;
      }
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    getConfig(val) {
      if (!val) return;
      getConfig(this.loginForm.account).then(res => {
        this.needCode = !!res.data.enableVerificationCode;
        if (this.needCode) {
          this.codeLength = res.data.verificationCodeNumber || 4;
          this.changeImg();
        }
      });
    },
    handleLogin() {
      if (this.loading) return;
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.$store.commit("user/SET_LOGIN_LOADING", true);
          const query = {
            ...this.loginForm,
            timestamp: this.timestamp
          };
          this.$store
            .dispatch("user/login", query)
            .then(res => {
              this.$router.push({
                // 登录成功以后跳转
                // path: this.redirect || '/home',
                path: this.redirect || "/dashboard",
                query: this.otherQuery
              });
            })
            .catch(() => {
              this.$store.commit("user/SET_LOGIN_LOADING", false);
            });
        } else {
          return false;
        }
      });
    },
    changeImg() {
      let timestamp = Math.random();
      this.timestamp = timestamp;
      this.imgUrl = `/api/oauth/ImageCode/${this.codeLength || 4}/${timestamp}`;
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    }
  }
};
</script>
